import React, { useEffect, useState, useCallback } from 'react'
import {
    View,
    ScrollView,
    SafeAreaView,
    TouchableOpacity,
    Alert,
    Image,
    TextInput,
    Modal,
} from 'react-native'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { leaveDetailStyles } from '../../styles/leaveDetailStyles'
import { Card, Text, Icon } from '@rneui/themed'
import { useRoute, useNavigation } from '@react-navigation/native'
import { RegisterApi, RegisterFileApi, ReasonFormApi, RegisterVO, LeaveStatus, ReasonFormData } from '../../api/leave'
import { ProcessInstanceApi, ApprovalNodeInfo } from '../../api/process'
import ProcessTimeline from '../../components/ProcessTimeline'
import ImagePreviewModal from '../../components/ImagePreviewModal'
import StatusIcon from './components/StatusIcon'
import { formatDate } from '../../utils/dateFormatter'
import { useLeaveDict } from '../../hooks/useDict'
import { DICT_TYPE } from '../../api/dict'
import ApprovalButtons from './components/ApprovalButtons'

interface LeaveDetailRouteProp {
    leaveId: number
    processInstanceId?: string
    isFromTodo?: boolean // 是否来自待批请假
    isFromDone?: boolean // 是否来自已批请假
    taskId?: string // 任务ID，用于审批操作
    onRefresh?: () => void // 刷新回调函数
}

// 骨架屏组件
const SkeletonCard: React.FC<{ height?: number }> = ({ height = 100 }) => (
    <Card containerStyle={leaveDetailStyles.cardContainer}>
        <View style={[leaveDetailStyles.skeletonBox, { height }]} />
        <View style={[leaveDetailStyles.skeletonLine, leaveDetailStyles.skeletonLineLarge]} />
        <View style={[leaveDetailStyles.skeletonLine, leaveDetailStyles.skeletonLineSmall]} />
    </Card>
)

// 请假事由类型枚举
enum ReasonType {
    RESEARCH = 1,      // 调研
    TRAINING = 2,      // 培训
    BUSINESS = 3,      // 公务
    PERSONAL = 4,      // 因私
    ACADEMIC = 5,      // 学术会议
    OTHER = 6          // 其他
}

// 请假事由类型标签
const getReasonTypeLabel = (type: number): string => {
    switch (type) {
        case ReasonType.RESEARCH:
            return '调研'
        case ReasonType.TRAINING:
            return '培训'
        case ReasonType.BUSINESS:
            return '公务'
        case ReasonType.PERSONAL:
            return '因私'
        case ReasonType.ACADEMIC:
            return '学术会议'
        case ReasonType.OTHER:
            return '其他'
        default:
            return '未知'
    }
}

const LeaveDetail: React.FC = () => {
    const route = useRoute<any>()
    const navigation = useNavigation<any>()
    const { leaveId, isFromTodo, isFromDone, taskId, onRefresh } = route.params as LeaveDetailRouteProp
    const insets = useSafeAreaInsets()
    
    // 使用字典Hook获取请假相关字典数据
    const { getDictLabel, loading: dictLoading } = useLeaveDict()
    
    const [leaveData, setLeaveData] = useState<RegisterVO | null>(null)
    const [reasonForms, setReasonForms] = useState<ReasonFormData[]>([])
    const [attachments, setAttachments] = useState<any[]>([])
    const [processNodes, setProcessNodes] = useState<ApprovalNodeInfo[]>([])
    const [processInstanceStatus, setProcessInstanceStatus] = useState<number | null>(null)
    
    // 分别控制不同部分的加载状态
    const [loadingStates, setLoadingStates] = useState({
        basic: true,        // 基本信息
        reasons: true,      // 请假事由
        attachments: true,  // 附件
        process: true,      // 流程信息
    })
    
    const [expandedReasons, setExpandedReasons] = useState<Set<number>>(new Set())
    const [expandedWorkArrangement, setExpandedWorkArrangement] = useState(false)
    
    // 图片预览相关状态
    const [showImagePreview, setShowImagePreview] = useState(false)
    const [previewImage, setPreviewImage] = useState<{url: string, name: string} | null>(null)
    
    // 取消申请相关状态
    const [showCancelModal, setShowCancelModal] = useState(false)
    const [cancelReason, setCancelReason] = useState('')

    // 获取请假详情
    const fetchLeaveDetail = useCallback(async () => {
        try {
            // 重置加载状态
            setLoadingStates({
                basic: true,
                reasons: true,
                attachments: true,
                process: true,
            })
            
            // 第一步：优先加载基本信息
            const basicDataPromise = RegisterApi.getRegister(leaveId).then(response => {
                if (response && response.data) {
                    setLeaveData(response.data)
                    setLoadingStates(prev => ({ ...prev, basic: false }))
                }
                return response
            }).catch(error => {
                console.error('获取请假基本信息失败:', error)
                setLoadingStates(prev => ({ ...prev, basic: false }))
                throw error
            })

            // 第二步：并行加载其他数据（非阻塞）
            const loadSecondaryData = async () => {
                // 并行加载请假事由、附件
                const secondaryPromises = [
                    // 请假事由
                    ReasonFormApi.getReasonFormList(leaveId).then(response => {
                        if (response && response.data) {
                            setReasonForms(response.data)
                        }
                        setLoadingStates(prev => ({ ...prev, reasons: false }))
                    }).catch(error => {
                        console.error('获取请假事由失败:', error)
                        setLoadingStates(prev => ({ ...prev, reasons: false }))
                    }),

                    // 附件
                    RegisterFileApi.getRegisterFile(leaveId).then(response => {
                        if (response && response.code === 0 && response.data && Array.isArray(response.data)) {
                            setAttachments(response.data)
                        }
                        setLoadingStates(prev => ({ ...prev, attachments: false }))
                    }).catch(error => {
                        console.error('获取请假附件失败:', error)
                        setLoadingStates(prev => ({ ...prev, attachments: false }))
                    })
                ]

                // 等待基本信息加载完成后再加载流程信息
                try {
                    const basicResponse = await basicDataPromise
                    
                    if (basicResponse?.data?.processInstanceId) {
                        secondaryPromises.push(
                            // 获取流程详情（包含状态）
                            ProcessInstanceApi.getProcessInstance(basicResponse.data.processInstanceId).then(response => {
                                if (response?.code === 0 && response.data) {
                                    setProcessInstanceStatus(response.data.status)
                                }
                            }).catch(error => {
                                console.error('获取流程实例状态失败:', error)
                            }),
                            
                            // 获取流程节点信息
                            ProcessInstanceApi.getApprovalDetail({
                                processInstanceId: basicResponse.data.processInstanceId
                            }).then(response => {
                                const responseData = response.data as any
                                if (response?.code === 0 && responseData?.activityNodes) {
                                    setProcessNodes(responseData.activityNodes)
                                    // console.log(processNodes)
                                } else {
                                    setProcessNodes([])
                                }
                                setLoadingStates(prev => ({ ...prev, process: false }))
                            }).catch(error => {
                                console.error('获取流程信息失败:', error)
                                setProcessNodes([])
                                setLoadingStates(prev => ({ ...prev, process: false }))
                            })
                        )
                    } else {
                        setProcessNodes([])
                        setLoadingStates(prev => ({ ...prev, process: false }))
                    }
                } catch (error) {
                    setLoadingStates(prev => ({ ...prev, process: false }))
                }

                // 等待所有次要数据加载完成
                await Promise.allSettled(secondaryPromises)
            }

            // 启动次要数据加载（不等待）
            loadSecondaryData()

        } catch (error) {
            console.error('获取请假详情失败:', error)
            Alert.alert('错误', '获取请假详情失败')
            setLoadingStates({
                basic: false,
                reasons: false,
                attachments: false,
                process: false,
            })
        }
    }, [leaveId])

    // 获取请假详情
    useEffect(() => {
        if (leaveId) {
            fetchLeaveDetail()
        }
    }, [leaveId, fetchLeaveDetail])

    // 处理取消申请
    const handleCancelApplication = () => {
        setCancelReason('')
        setShowCancelModal(true)
    }
    
    // 提交取消申请
    const handleSubmitCancel = async () => {
        try {
            if (!cancelReason.trim()) {
                Alert.alert('提示', '请输入取消原因')
                return
            }
            
            if (!leaveData?.processInstanceId) {
                Alert.alert('错误', '缺少流程实例ID，无法取消申请')
                return
            }
            
            // 调用取消申请API
            await ProcessInstanceApi.cancelProcessInstanceByStartUser(
                leaveData.processInstanceId,
                cancelReason.trim()
            )
            
            Alert.alert('成功', '申请已取消', [
                { text: '确定', onPress: () => {
                    // 关闭弹窗并返回上一页
                    setShowCancelModal(false)
                    navigation.goBack()
                    // TODO:
                }}
            ])
        } catch (error) {
            console.error('取消申请失败:', error)
            Alert.alert('错误', '取消申请失败，请稍后重试')
        }
    }
    
    // 关闭取消申请弹窗
    const handleCloseCancelModal = () => {
        setShowCancelModal(false)
        setCancelReason('')
    }

    // 处理再次申请
    const handleApplyAgain = () => {
        navigation.navigate('LeaveAdd')
    }

    // 处理图片预览
    const handleImagePreview = (imageUrl: string, imageName: string) => {
        if (imageUrl) {
            setPreviewImage({ url: imageUrl, name: imageName })
            setShowImagePreview(true)
        }
    }

    // 处理事由展开/折叠
    const toggleReasonExpansion = (reasonId: number) => {
        setExpandedReasons(prev => {
            const newSet = new Set(prev)
            if (newSet.has(reasonId)) {
                newSet.delete(reasonId)
            } else {
                newSet.add(reasonId)
            }
            return newSet
        })
    }

    // 处理工作安排展开/折叠
    const toggleWorkArrangementExpansion = () => {
        setExpandedWorkArrangement(prev => !prev)
    }

    // 渲染请假事由详情
    const renderReasonDetails = () => {
        // 如果正在加载，显示骨架屏
        if (loadingStates.reasons) {
            return (
                <View style={leaveDetailStyles.reasonSection}>
                    <Text style={leaveDetailStyles.reasonSectionTitle}>请假事由详情</Text>
                    <View style={leaveDetailStyles.skeletonBox} />
                </View>
            )
        }

        if (!reasonForms || reasonForms.length === 0) {
            return (
                <View style={leaveDetailStyles.reasonSection}>
                    <Text style={leaveDetailStyles.reasonSectionTitle}>请假事由</Text>
                    <Text style={leaveDetailStyles.noDateText}>暂无详细事由信息</Text>
                </View>
            )
        }

        // 按类型分组
        const groupedReasons = reasonForms.reduce((groups, reason) => {
            const type = reason.type || 0
            if (!groups[type]) {
                groups[type] = []
            }
            groups[type].push(reason)
            return groups
        }, {} as Record<number, ReasonFormData[]>)

        return (
            <View style={leaveDetailStyles.reasonSection}>
                <Text style={leaveDetailStyles.reasonSectionTitle}>请假事由详情</Text>
                {Object.entries(groupedReasons).map(([type, reasons]) => {
                    const reasonType = getReasonTypeLabel(parseInt(type, 10))
                    const groupId = parseInt(type, 10)
                    const isExpanded = expandedReasons.has(groupId)
                    const hasMultipleReasons = reasons.length > 1
                    
                    return (
                        <View key={groupId} style={leaveDetailStyles.reasonItem}>
                            <TouchableOpacity 
                                style={leaveDetailStyles.reasonHeader}
                                onPress={() => toggleReasonExpansion(groupId)}
                                activeOpacity={0.7}
                            >
                                <Text style={leaveDetailStyles.reasonTypeTitle}>{reasonType}</Text>
                                <Icon 
                                    name={isExpanded ? "chevron-up" : "chevron-down"} 
                                    type="feather" 
                                    size={20} 
                                    color="#666" 
                                />
                            </TouchableOpacity>
                            
                            {isExpanded && (
                                <View style={leaveDetailStyles.reasonContent}>
                                    {reasons.map((reason, index) => (
                                        <View key={reason.id || index} style={leaveDetailStyles.researchItem}>
                                            <View style={leaveDetailStyles.researchBullet}>
                                                <View style={leaveDetailStyles.bulletPoint} />
                                                {hasMultipleReasons && index < reasons.length - 1 && (
                                                    <View style={leaveDetailStyles.bulletLine} />
                                                )}
                                            </View>
                                            <View style={leaveDetailStyles.researchContent}>
                                                <View style={leaveDetailStyles.titleDateRow}>
                                                    <Text style={leaveDetailStyles.researchTitle}>
                                                        {reason.type === 6 ? '其他' : `${reasonType}${index + 1}`}
                                                    </Text>
                                                    {reason.startDate && reason.endDate && (
                                                        <Text style={leaveDetailStyles.researchDate}>
                                                            {formatDate(reason.startDate)}至{formatDate(reason.endDate)}
                                                        </Text>
                                                    )}
                                                </View>
                                                {/* 根据不同类型显示不同字段 */}
                                                {reason.type === 1 && ( // 调研
                                                    <>
                                                        {reason.subject && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                调研主题：{reason.subject}
                                                            </Text>
                                                        )}
                                                        {reason.purpose && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                调研目的：{reason.purpose}
                                                            </Text>
                                                        )}
                                                        {reason.unit && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                调研单位：{reason.unit}
                                                            </Text>
                                                        )}
                                                    </>
                                                )}
                                                
                                                {reason.type === 2 && ( // 培训
                                                    <>
                                                        {reason.subject && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                培训主题：{reason.subject}
                                                            </Text>
                                                        )}
                                                        {reason.unit && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                培训单位：{reason.unit}
                                                            </Text>
                                                        )}
                                                    </>
                                                )}
                                                
                                                {reason.type === 3 && ( // 公务
                                                    <>
                                                        {reason.subject && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                会议名称：{reason.subject}
                                                            </Text>
                                                        )}
                                                        {reason.unit && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                主办单位：{reason.unit}
                                                            </Text>
                                                        )}
                                                    </>
                                                )}
                                                
                                                {reason.type === 4 && ( // 因私
                                                    <>
                                                        {reason.privateType !== undefined && reason.privateType !== null && reason.privateType !== '' && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                请假类型：{getDictLabel(DICT_TYPE.PERSONAL_TYPE, Number(reason.privateType)) || String(reason.privateType)}
                                                            </Text>
                                                        )}
                                                        {reason.detail && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                请假详情：{reason.detail}
                                                            </Text>
                                                        )}
                                                        {reason.phone && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                联系电话：{reason.phone}
                                                            </Text>
                                                        )}
                                                        {reason.visitRoute && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                探亲路线：{reason.visitRoute}
                                                            </Text>
                                                        )}
                                                        {reason.relationship && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                与探望人关系：{reason.relationship}
                                                            </Text>
                                                        )}
                                                        {reason.visitedPersonName && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                被探望人姓名：{reason.visitedPersonName}
                                                            </Text>
                                                        )}
                                                        {reason.visitType !== undefined && reason.visitType !== null && reason.visitType !== '' && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                探亲类别：{getDictLabel(DICT_TYPE.PERSONAL_VISIT_TYPE, Number(reason.visitType)) || String(reason.visitType)}
                                                            </Text>
                                                        )}
                                                        {reason.registeredAddress && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                户口地：{reason.registeredAddress}
                                                            </Text>
                                                        )}
                                                        {reason.maritalStatus !== undefined && reason.maritalStatus !== null && reason.maritalStatus !== '' && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                婚姻状况：{getDictLabel(DICT_TYPE.MARITAL_STATUS, Number(reason.maritalStatus)) || String(reason.maritalStatus)}
                                                            </Text>
                                                        )}
                                                        {reason.birthCount !== undefined && reason.birthCount !== null && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                生育次数：{String(reason.birthCount)}
                                                            </Text>
                                                        )}
                                                        {reason.multipleBirth !== undefined && reason.multipleBirth !== null && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                是否多胞胎：{getDictLabel(DICT_TYPE.IS_PRESENTATION, Number(reason.multipleBirth)) || String(reason.multipleBirth)}
                                                            </Text>
                                                        )}
                                                        {reason.difficultBirth !== undefined && reason.difficultBirth !== null && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                是否难产：{getDictLabel(DICT_TYPE.IS_PRESENTATION, Number(reason.difficultBirth)) || String(reason.difficultBirth)}
                                                            </Text>
                                                        )}
                                                    </>
                                                )}
                                                
                                                {reason.type === 5 && ( // 学术会议
                                                    <>

                                                        {reason.subject !== undefined && reason.subject !== null && reason.subject !== '' && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                会议名称：{reason.subject}
                                                            </Text>
                                                        )}
                                                        {reason.unit !== undefined && reason.unit !== null && reason.unit !== '' && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                主办方：{reason.unit}
                                                            </Text>
                                                        )}
                                                        {reason.meetingNature !== undefined && reason.meetingNature !== null && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                会议性质：{getDictLabel(DICT_TYPE.ACADEMIC_NATURE, Number(reason.meetingNature)) || String(reason.meetingNature)}
                                                            </Text>
                                                        )}
                                                        <Text style={leaveDetailStyles.researchField}>
                                                            是否受邀作报告：{reason.reportTitle ? '是' : '否'}
                                                        </Text>
                                                        {reason.reportType !== undefined && reason.reportType !== null && reason.reportType !== '' && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                报告类型：{getDictLabel(DICT_TYPE.REPORT_TYPE, Number(reason.reportType)) || String(reason.reportType)}
                                                            </Text>
                                                        )}
                                                        {reason.reportTitle !== undefined && reason.reportTitle !== null && reason.reportTitle !== '' && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                报告题目：{reason.reportTitle}
                                                            </Text>
                                                        )}
                                                        {reason.reportPaperCount !== undefined && reason.reportPaperCount !== null && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                交流论文数：{String(reason.reportPaperCount)}
                                                            </Text>
                                                        )}
                                                    </>
                                                )}
                                                
                                                {reason.type === 6 && ( // 其他
                                                    <>
                                                        {reason.detail && (
                                                            <Text style={leaveDetailStyles.researchField}>
                                                                其他事由：{reason.detail}
                                                            </Text>
                                                        )}
                                                    </>
                                                )}
                                            </View>
                                        </View>
                                    ))}
                                </View>
                            )}
                        </View>
                    )
                })}
            </View>
        )
    }

    // 渲染附件信息
    const renderAttachments = () => {
        // 如果正在加载，显示骨架屏
        if (loadingStates.attachments) {
            return (
                <View style={leaveDetailStyles.reasonSection}>
                    <Text style={leaveDetailStyles.reasonSectionTitle}>附件</Text>
                    <View style={leaveDetailStyles.skeletonBox} />
                </View>
            )
        }

        if (!attachments || attachments.length === 0) {
            return null
        }

        return (
            <View style={leaveDetailStyles.reasonSection}>
                <Text style={leaveDetailStyles.reasonSectionTitle}>附件 ({attachments.length})</Text>
                
                {attachments.map((file, index) => {
                    // 判断是否为图片文件
                    const isImage = file.leaveFileName && /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(file.leaveFileName)

                    return (
                        <View key={file.id || index} style={leaveDetailStyles.attachmentItem}>
                            {isImage ? (
                                // 如果是图片，显示图片预览
                                <TouchableOpacity 
                                    style={leaveDetailStyles.imagePreviewContainer}
                                    onPress={() => handleImagePreview(file.leaveFileUrl, file.leaveFileName)}
                                >
                                    <Image 
                                        source={{ uri: file.leaveFileUrl }}
                                        style={leaveDetailStyles.imagePreview}
                                        resizeMode="cover"
                                    />
                                    <View style={leaveDetailStyles.imageInfo}>
                                        <Text style={leaveDetailStyles.imageFileName}>
                                            {file.leaveFileName || `图片${index + 1}`}
                                        </Text>
                                        {file.leaveFileSize && (
                                            <Text style={leaveDetailStyles.imageFileSize}>
                                                {(file.leaveFileSize / 1024).toFixed(1)} KB
                                            </Text>
                                        )}
                                    </View>
                                </TouchableOpacity>
                            ) : (
                                // 如果不是图片，显示文件图标
                                <>
                                    <Icon name="file" type="feather" size={16} color="#666" />
                                    <View style={leaveDetailStyles.imageInfo}>
                                        <Text style={leaveDetailStyles.fileName}>
                                            {file.leaveFileName || `附件${index + 1}`}
                                        </Text>
                                        {file.leaveFileSize && (
                                            <Text style={leaveDetailStyles.fileSize}>
                                                {(file.leaveFileSize / 1024).toFixed(1)} KB
                                            </Text>
                                        )}
                                    </View>
                                </>
                            )}
                        </View>
                    )
                })}
            </View>
        )
    }

    // 整体加载状态
    const isMainLoading = loadingStates.basic
    const hasAnyData = leaveData !== null

    if (isMainLoading || dictLoading) {
        return (
            <SafeAreaView style={leaveDetailStyles.container}>
                <ScrollView style={leaveDetailStyles.scrollView}>
                    <SkeletonCard height={120} />
                    <SkeletonCard height={200} />
                    <SkeletonCard height={150} />
                </ScrollView>
            </SafeAreaView>
        )
    }

    if (!hasAnyData) {
        return (
            <SafeAreaView style={leaveDetailStyles.container}>
                <View style={leaveDetailStyles.loadingContainer}>
                    <Text>未找到请假记录</Text>
                </View>
            </SafeAreaView>
        )
    }

    return (
        <SafeAreaView style={leaveDetailStyles.container}>
            <ScrollView 
                style={leaveDetailStyles.scrollView}
                contentContainerStyle={{ paddingBottom: 10 + Math.max(insets.bottom, 16) }}
            >
                <Card containerStyle={leaveDetailStyles.cardContainer}>
                    <View style={leaveDetailStyles.cardHeader}>
                        <View style={leaveDetailStyles.cardLeftContent}>
                            <Text style={leaveDetailStyles.cardTitle}>
                                {leaveData.nickName || '未知用户'}的请假申请
                            </Text>
                            <Text style={leaveDetailStyles.departmentText}>
                                所在部门: {leaveData.deptName || '未知部门'}
                            </Text>
                        </View>
                        <View style={leaveDetailStyles.cardRightContent}>
                            {processInstanceStatus !== null && (
                                <StatusIcon 
                                    status={processInstanceStatus}
                                    size={80}
                                    showText={false}
                                />
                            )}
                        </View>
                    </View>
                </Card>

                <Card containerStyle={leaveDetailStyles.cardContainer}>
                    <Text style={leaveDetailStyles.cardTitle}>行程</Text>
                    <View style={leaveDetailStyles.infoRow}>
                        <Text style={leaveDetailStyles.infoLabel}>起止日期：</Text>
                        <Text style={leaveDetailStyles.infoValue}>
                            {formatDate(leaveData.startDate)} 至 {formatDate(leaveData.endDate)}
                        </Text>
                    </View>
                    {leaveData.destination && (
                        <View style={leaveDetailStyles.infoRow}>
                            <Text style={leaveDetailStyles.infoLabel}>前往地点：</Text>
                            <View style={leaveDetailStyles.infoValue}>
                                {leaveData.destination.split('|||').map((dest, index, array) => (
                                    <View key={index}>
                                        <Text style={leaveDetailStyles.destinationText}>
                                            {dest.trim()}
                                        </Text>
                                        {index < array.length - 1 && (
                                            <View style={leaveDetailStyles.destinationDivider} />
                                        )}
                                    </View>
                                ))}
                            </View>
                        </View>
                    )}
                    {/* <View style={leaveDetailStyles.infoRow}>
                        <Text style={leaveDetailStyles.infoLabel}>请假类型：</Text>
                        <Text style={leaveDetailStyles.infoValue}>
                            {leaveData.reasons || '事假'}
                        </Text>
                    </View> */}
                    {/* 请假事由详情 */}
                    {renderReasonDetails()}

                    {/* 备注信息 */}
                    {leaveData.remark && (
                        <View style={leaveDetailStyles.reasonSection}>
                            <Text style={leaveDetailStyles.reasonSectionTitle}>备注</Text>
                            <View style={leaveDetailStyles.reasonItem}>
                                <View style={leaveDetailStyles.reasonContent}>
                                    <Text style={leaveDetailStyles.researchField}>
                                        {leaveData.remark}
                                    </Text>
                                </View>
                            </View>
                        </View>
                    )}

                    {/* 工作安排 */}
                    {leaveData.hostArrangement && (
                        <View style={leaveDetailStyles.reasonSection}>
                            <TouchableOpacity 
                                style={leaveDetailStyles.cardHeader}
                                onPress={() => toggleWorkArrangementExpansion()}
                                activeOpacity={0.7}
                            >
                                <Text style={leaveDetailStyles.reasonSectionTitle}>请假期间主持工作负责人安排</Text>
                                <Icon 
                                    name={expandedWorkArrangement ? "chevron-up" : "chevron-down"} 
                                    type="feather" 
                                    size={20} 
                                    color="#666" 
                                />
                            </TouchableOpacity>
                            
                            {expandedWorkArrangement && (
                                <View style={leaveDetailStyles.reasonItem}>
                                    <View style={leaveDetailStyles.reasonContent}>
                                        <Text style={leaveDetailStyles.researchField}>
                                            {leaveData.hostArrangement}
                                        </Text>
                                    </View>
                                </View>
                            )}
                        </View>
                    )}

                    {/* 附件信息 */}
                    {renderAttachments()}
                </Card>

                {/* 流程信息 */}
                {loadingStates.process ? (
                    <Card containerStyle={leaveDetailStyles.cardContainer}>
                        <Text style={leaveDetailStyles.cardTitle}>流程信息</Text>
                        <View style={leaveDetailStyles.skeletonBox} />
                    </Card>
                ) : (
                    <ProcessTimeline 
                        activityNodes={processNodes}
                        title="流程信息"
                        emptyText="暂无流程信息"
                    />
                )}
            </ScrollView>

            {/* 底部操作按钮 */}
            {!isFromDone && (
                <View style={[leaveDetailStyles.bottomActions, { paddingBottom: Math.max(insets.bottom, 16) }]}>
                    {isFromTodo ? (
                        // 待批请假：显示同意和不同意按钮
                        <ApprovalButtons
                            taskId={taskId!}
                            onApprovalComplete={() => {
                                // 调用刷新回调
                                onRefresh?.()
                                // 返回上一页
                                navigation.goBack()
                            }}
                            showFullWidth={false}
                        />
                    ) : (
                        // 我的请假：显示取消申请和再次申请按钮
                        <>
                            {/* 取消申请按钮：只有发起人且流程未结束时显示 */}
                            {leaveData.processInstanceId && 
                             leaveData.status !== LeaveStatus.COMPLETED && 
                             leaveData.status !== LeaveStatus.REJECTED && 
                             leaveData.status !== LeaveStatus.CANCELLED && (
                                <TouchableOpacity 
                                    style={leaveDetailStyles.cancelButton} 
                                    onPress={handleCancelApplication}
                                >
                                    <Icon name="rotate-ccw" type="feather" size={16} color="#666" />
                                    <Text style={leaveDetailStyles.cancelButtonText}>取消申请</Text>
                                </TouchableOpacity>
                            )}
                            
                            {/* 再次申请按钮：流程结束后显示 */}
                            {(leaveData.status === LeaveStatus.COMPLETED || 
                              leaveData.status === LeaveStatus.REJECTED || 
                              leaveData.status === LeaveStatus.CANCELLED) && (
                                <TouchableOpacity 
                                    style={leaveDetailStyles.applyButton} 
                                    onPress={handleApplyAgain}
                                >
                                    <Icon name="file-plus" type="feather" size={16} color="#fff" />
                                    <Text style={leaveDetailStyles.applyButtonText}>再次申请</Text>
                                </TouchableOpacity>
                            )}
                        </>
                    )}
                </View>
            )}
            
            {/* 图片预览 Modal */}
            <ImagePreviewModal
                visible={showImagePreview}
                imageUrl={previewImage?.url}
                imageName={previewImage?.name}
                onClose={() => setShowImagePreview(false)}
            />
            
            {/* 取消申请弹窗 */}
            <Modal
                visible={showCancelModal}
                transparent={true}
                animationType="fade"
                onRequestClose={handleCloseCancelModal}
            >
                <View style={leaveDetailStyles.modalOverlay}>
                    <View style={leaveDetailStyles.modalContent}>
                        <Text style={leaveDetailStyles.modalTitle}>取消申请</Text>
                        
                        <Text style={[leaveDetailStyles.modalTitle, leaveDetailStyles.modalSubTitle]}>
                            取消后，该审批流程将自动结束
                        </Text>
                        
                        <TextInput
                            style={leaveDetailStyles.modalInput}
                            placeholder="请输入取消原因"
                            value={cancelReason}
                            onChangeText={setCancelReason}
                            multiline={true}
                            numberOfLines={4}
                            textAlignVertical="top"
                        />
                        
                        <View style={leaveDetailStyles.modalButtons}>
                            <TouchableOpacity 
                                style={[leaveDetailStyles.modalButton, leaveDetailStyles.modalCancelButton]} 
                                onPress={handleCloseCancelModal}
                            >
                                <Text style={leaveDetailStyles.modalCancelButtonText}>取消</Text>
                            </TouchableOpacity>
                            
                            <TouchableOpacity 
                                style={[leaveDetailStyles.modalButton, leaveDetailStyles.modalApproveButton]} 
                                onPress={handleSubmitCancel}
                            >
                                <Text style={leaveDetailStyles.modalButtonText}>确认</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </Modal>
        </SafeAreaView>
    )
}

export default LeaveDetail
